package com.zrt.springboot.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrt.springboot.common.Result;
import com.zrt.springboot.entity.River;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.zrt.springboot.service.IAlertDataService;
import com.zrt.springboot.entity.AlertData;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 青哥哥
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/alert-data")
public class AlertDataController {

    @Resource
    private IAlertDataService alertDataService;

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<AlertData> list = alertDataService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "序列号");
        writer.addHeaderAlias("sensorId", "传感器id");
        writer.addHeaderAlias("depth", "河流水位(m)");
        writer.addHeaderAlias("time", "时间");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("河流水位预警信息报表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody AlertData alertData) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long l = Long.parseLong(alertData.getTime());
        alertData.setTime(format.format(l));
        return Result.success(alertDataService.saveOrUpdate(alertData));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
            return Result.success(alertDataService.removeById(id));
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
            return Result.success(alertDataService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
            return Result.success(alertDataService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
            return Result.success(alertDataService.getById(id));
    }

    @GetMapping("/all")
    public Result findAll( @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<AlertData> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        return Result.success(alertDataService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam String sensorId,
                           @RequestParam long startDateAndTime,
                           @RequestParam long endDateAndTime
                           ) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = format.format(startDateAndTime);
        String endTime = format.format(endDateAndTime);
        if (startDateAndTime == 0 && endDateAndTime == 0 && "".equals(sensorId)){
            Page<AlertData> page = alertDataService.page(new Page<>(pageNum, pageSize));
            return Result.success(page);
        }else {
            QueryWrapper<AlertData> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sensor_id",sensorId).between("time",startTime,endTime);
            Page<AlertData> page = alertDataService.page(new Page<>(pageNum, pageSize), queryWrapper);
            return Result.success(page);
        }

    }

}

